﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using Lamex.Interface;
using Lamex.mLabor.Common;
using Lamex.Common;

namespace Lamex.mLabor.UI
{
    public partial class frmLBR_LaborTime_Workstation : frmBaseChild
    {
        string strSql;
        DataTable dt;

        public frmLBR_LaborTime_Workstation()
        {
            InitializeComponent();
        }

        private void frmLBR_LaborTime_Workstation_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            dateEdit1.DateTime = DateTime.Now.AddDays(-1);

            //GridView输入数据，按回车自动跳到下一列设置方法，按下Enter键将焦点移至下一单元格
            //gridView1.OptionsNavigation.EnterMoveNextColumn = true;
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            //刷新站点工时维护数据
            string strSub_Fatory = comboBoxEdit1.Text.ToString();
            string strStationFilter ="";
            switch(strSub_Fatory)
            {
                case "生产-桌子":
                    strStationFilter = "WORK_STATION LIKE 'DXX_%'";
                    break;
                case "生产-屏风":
                    strStationFilter = "WORK_STATION LIKE 'PXX_%'";
                    break;
                case "生产-椅子":
                    strStationFilter = "WORK_STATION LIKE 'SXX_%'";
                    break;
                case "生产-MCG":
                    strStationFilter = "WORK_STATION LIKE 'MXX_%' OR WORK_STATION LIKE 'TXX_%'";
                    break;
                default:
                    strStationFilter = "1=1";
                    break;
            }
            strSql = @"SELECT c.WORKSTATION,REF_LABORTIME,REF_LABORTIME AS CUR_LABORTIME
FROM OP_MGT_Factory_Workstation AS c
LEFT JOIN
(SELECT WORKSTATION,WORK_HOURS AS REF_LABORTIME
FROM OP_MGT_Factory_Workstation AS a
LEFT JOIN HR_Work_Hours_Workstation AS b
ON a.WORKSTATION=b.WORK_STATION 
AND WORK_DATE IN (
SELECT MAX(WORK_DATE) FROM HR_Work_Hours_Workstation
WHERE " + strStationFilter + @")) AS d
ON c.WORKSTATION=d.WORKSTATION
WHERE SUB_FACTORY='" + comboBoxEdit1.Text.ToString() + @"'";

            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
            gridControl1.DataSource = dt;

            gridView1.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView1.Columns[0].SummaryItem.DisplayFormat = "计数:";
            gridView1.Columns[1].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            //gridView1.Columns[1].SummaryItem.DisplayFormat = "{0:N}";//两位小数
            gridView1.Columns[1].SummaryItem.DisplayFormat = "{0:N0}";//无小数位

        }

        private void addDataToGridControl(DataTable dt, DevExpress.XtraGrid.GridControl gc, DevExpress.XtraGrid.Views.Grid.GridView gv)
        {
            //if (dt.Rows.Count > 0)
            //{
            gc.DataSource = dt;
            gv.OptionsBehavior.Editable = false;
            gv.OptionsView.ColumnAutoWidth = true;
            //}

            //gridView1页脚汇总设置
            gv.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gv.Columns[0].SummaryItem.DisplayFormat = "计数:";
            gv.Columns[1].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            //gv.Columns[1].SummaryItem.DisplayFormat = "{0:N}";//两位小数
            gv.Columns[1].SummaryItem.DisplayFormat = "{0:N0}";//无小数位
        }

        private void sbtnSave_Click(object sender, EventArgs e)
        {

            this.gridView1.CloseEditor();
            this.gridView1.UpdateCurrentRow();
            //将gridView1数据写入到【HR_Work_Hours_Workstation】表中
            if (gridView1.RowCount < 0) return;
            DataTable dtView = ((DataView)gridView1.DataSource).ToTable();
            DataTable temp = new DataTable();
            temp.Columns.Add("WORK_DATE", typeof(DateTime));
            temp.Columns.Add("WORK_STATION", typeof(string));
            temp.Columns.Add("WORK_HOURS", typeof(decimal)); 
            temp.Columns.Add("UPDATE_TIME", typeof(DateTime));
            temp.Columns.Add("UPDATE_USER", typeof(string));
            foreach(DataRow d in dtView.Rows)
            {
                DataRow dr = temp.NewRow();
                dr["WORK_DATE"] = dateEdit1.Text;
                dr["WORK_STATION"] = d["WORKSTATION"];
                if(string.IsNullOrEmpty(d["CUR_LABORTIME"].ToString()))
                    dr["WORK_HOURS"] =0;
                else
                    dr["WORK_HOURS"] = d["CUR_LABORTIME"].ToString();
                dr["UPDATE_USER"] = Loginer.CurrentUser.AccountName ;
                dr["UPDATE_TIME"] = DateTime.Now ;
                if(dr["WORK_HOURS"].ToString()!="0")
                    temp.Rows.Add(dr);
            }
            GridViewSaveHelper.FindExcelToDataBase(temp, "HR_Work_Hours_Workstation");
        }

        public override void DoView(IButtonInfo sender)
        {
            comboBoxEdit1.Focus();
            sbtnView_Click(null, null);
            base.DoView(sender);
        }
        public override void DoSave(IButtonInfo sender)
        {
            sbtnSave_Click(null, null);
            base.DoSave(sender);
        }

        #region GridView动态显示关联数据

        //Dev GridView RowCellClick事件与MouseDown事件
        //https://www.kancloud.cn/tuctus/devexpresscourse/167505
        //不管这一列OptionsColumn.AllowEdit是不是false，只要这一列有MouseDown事件，就不会执行该列的RowCellClick事件。
        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            GridHitInfo hint = gridView1.CalcHitInfo(e.X, e.Y);
            if (gridView1.RowCount == 0 || /*记录数大于0*/
                    !hint.InRowCell /*有效的单元格*/||
                e.Button != MouseButtons.Left /*鼠标左键*/||
                    e.Clicks != 1  /*单击*/
                )
            {
                return;
            }
            //if (hint.Column.FieldName == "WORKSTATION") //需要弹出窗体的列名及该列的FieldName
            //{
                //强转当前行（避免鼠标点击的行与焦点行FocusedRowHandle不一致，鼠标点击时，焦点行FocusedRowHandle还未转换）
                gridView1.FocusedRowHandle = hint.RowHandle;
                
                //打开窗体的代码及处理略
                //如果获取到打开窗体的值之后，需要更新到GridView上使用
                // gViewActPara.SetRowCellValue(hint.RowHandle, "需要接受值列的FieldName",从窗体获取到的值);
                //使用SetRowCellValue会触发gViewActPara_CellValueChanged事件

                DataRow dr = gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//获取选中行
                string strWorkstation = gridView1.GetFocusedRowCellValue("WORKSTATION").ToString();//获取某一行的指定列的值

                //刷新站点工序对照数据，供用户参考
                strSql = @"SELECT WORKSTATION AS 工作站,PROCESS_CODE AS 工作中心,PROCESS_NAME AS 工序名称
FROM View_OP_Resource_Plan
WHERE WORKSTATION='" + strWorkstation + @"'";

                dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
                addDataToGridControl(dt, gridControl2, gridView2);
            //}
        }

        //gridView1.OptionsBehavior.Editable 必须设置成 false（全局），否则不触发左键单击事件，只触发右键单击
        //或者手工绑定数据，并将特定列的OptionsColumnr的Allowedit设成false（局部）
        //此模块中工作站、参考工时列会触发此事件，因其OptionsColumnr的Allowedit设成false
        //可以删除此事件，保留是为了说明RowCellClick的使用或触发方法
        //private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        //{
        //    //MessageBox.Show("Test Code!!!");

        //    //int iRow = 0;
        //    //iRow = e.RowHandle;
        //}

        #endregion

        #region Devexpress GridView控制Enter键时向下移动

        //https://blog.csdn.net/crazy2910/article/details/51957548?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-3

        /// <summary>
        /// 控制Enter键时向下移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int rowHandle = gridView1.FocusedRowHandle;
                if (gridView1.FocusedColumn.Caption == null) return;
                string coloumnName = gridView1.FocusedColumn.Caption;
                if (coloumnName.Contains("CUR_LABORTIME"))//指定的列
                {
                    rowHandle = rowHandle + 1;
                    if (rowHandle >= gridView1.RowCount)
                    {
                        //SetFocuse(gridView1, 0, coloumnName);
                    }
                    else
                    {
                        SetFocuse(gridView1, rowHandle, coloumnName);
                    }
                    gridView1.UpdateCurrentRow();
                }


            }
        }

        /// <summary>
        /// 设置某单元格获得焦点
        /// </summary>
        /// <param name="view"></param>
        /// <param name="rowHandle"></param>
        /// <param name="columnName"></param>
        private void SetFocuse(DevExpress.XtraGrid.Views.Grid.GridView view, Int32 rowHandle, string columnName)
        {
            view.Focus();
            view.FocusedRowHandle = rowHandle;
            view.FocusedColumn = view.Columns[columnName];
            view.ShowEditor();
            
        }

        #endregion

        private void gridControl1_EditorKeyUp(object sender, KeyEventArgs e)
        {
            
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //gridView1.UpdateCurrentRow();
        }
    }
}